package main

import (
	"fmt"
	"github.com/eatmoreapple/openwechat"
	"goocr/config"
	"goocr/data_treating"
	"goocr/img_ocr"
	"goocr/rebot"
	"goocr/util"
	"os"
	"time"
)

var bot *openwechat.Bot

func main() {
	go func() {
		//ocr图片
		TimeTickerStart(img_ocr.ImgOcr, HourNoticeMsg)
	}()

	//机器人 https://openwechat.readthedocs.io/zh/latest/
	WechatRebot()
}

// TimeTickerStart
// @Description: 执行定时任务
// @param param
func TimeTickerStart(f1 func(), f2 func(string)) {
	nType2 := 0
	nType3 := 0
	nType4 := 0
	c1 := time.NewTicker(time.Duration(config.Conf.Tim*60) * time.Minute)
	time.Sleep(30 * time.Second)
	c2 := time.NewTicker(time.Duration(config.Conf.Tim*60) * time.Minute)
	for {
		select {
		case <-c1.C:
			f1()
		case <-c2.C:
			f2("1")
			if isMonday() {
				if nType2 == 0 {
					f2("2")
				}
				nType2++
			} else {
				if nType2 != 0 {
					nType2 = 0
				}
			}
			if isMonday() {
				if nType3 == 0 {
					f2("3")
					nType3++
				}
			} else {
				if nType3 != 0 {
					nType3 = 0
				}
			}
			if beginningOfMonth() {
				if nType4 == 0 {
					f2("4")
					nType4++
				}
			} else {
				if nType4 != 0 {
					nType4 = 0
				}
			}
		}
	}
}

// 月初
func beginningOfMonth() bool {
	now := time.Now()
	return now.AddDate(0, 0, -now.Day()+1).Format(data_treating.DateTimeFormat) == now.Format(data_treating.DateTimeFormat)
}

// 是否周一
func isMonday() bool {
	now := time.Now()
	return int(now.Weekday()) == 1
}

// 排行榜
func HourNoticeMsg(nType string) {
	if bot == nil {
		return
	}
	self, err := bot.GetCurrentUser()
	if err != nil {
		util.LogError(fmt.Sprintf("Failed to get current user", err))
		return
	}
	friends, err := self.Friends()
	if err != nil {
		util.LogError(fmt.Sprintf("Failed to get friends", err))
		return
	}
	father := friends.GetByRemarkName(config.Conf.CommentName)
	data, err := data_treating.RankingData(nType)
	if err != nil {
		util.LogError(fmt.Sprintf("获取排行榜出错:%v", err))
		return
	}
	var title string
	switch nType {
	case "1":
		title = "当天"
	case "2":
		title = "本周"
	case "3":
		title = "上周"
	default:
		title = "上月"
	}
	var str = fmt.Sprintf("%s排行榜\n\n", title)
	for _, item := range data {
		nickName := item.NickName
		if len([]rune(nickName)) > 4 {
			nickName = fmt.Sprintf("%s%s", string([]rune(nickName)[0:4]), "*")
		}
		str = str + fmt.Sprintf("%d %d %s %d\n", item.Ranking, item.UserId, nickName, item.TotalMark)
	}
	res, err1 := father.SendText(str)
	util.LogInfo(fmt.Sprintf("推送结果:%v,err:%v\n", res, err1))
}

func WechatRebot() {
	robotName := "robot"
	botCloseCh := make(chan bool)
	restartTicker := time.NewTicker(2 * time.Minute) // 设置5分钟的定时器
	removeFile(robotName)
	startRebot := func() {
		bot = rebot.LoginWechat(robotName)
		if bot == nil {
			util.LogError("机器人登录失败，重新尝试登录...")
			botCloseCh <- true
			return
		}
		util.LogInfo("机器人启动成功")
		rebot.WechatRobot(bot) //微信机器人
		go func() {
			select {
			case <-restartTicker.C:
				util.LogInfo("5分钟已过，检测bot")
				if !bot.Alive() {
					botCloseCh <- true
				}
			}
		}()
		if err := bot.Block(); err != nil {
			util.LogError(fmt.Sprintf("机器人出错:%v", err))
			botCloseCh <- true
		}
	}
	go startRebot()
	for {
		select {
		case <-botCloseCh:
			removeFile(robotName)
			util.LogInfo("重启已发送")
			time.Sleep(time.Second * 10) // 这个sleep是为了确保重新登录不是瞬间发生，可以根据需要调整或移除
			go startRebot()
		}
	}
}

func removeFile(robotName string) {
	filePath := fmt.Sprintf("%s.json", robotName)
	// 删除文件
	err := os.Remove(filePath)
	if err != nil && !os.IsNotExist(err) { // 不再报告“文件不存在”的错误
		util.LogError(fmt.Sprintf("删除文件%s错误:%v", filePath, err))
	} else {
		util.LogInfo(fmt.Sprintf("文件%s已成功删除!", filePath))
	}
}
